package com.aimuceliang.aimuceliang.ui.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aimuceliang.aimuceliang.Constants;
import com.aimuceliang.aimuceliang.dev.R;
import com.aimuceliang.aimuceliang.green_dao.LongChengDaoUtils;
import com.aimuceliang.aimuceliang.green_dao.TiChiCeLiang;
import com.aimuceliang.aimuceliang.green_dao.TiChiCeLiangDaoUtils;
import com.aimuceliang.aimuceliang.green_dao.WoChengDaoUtils;
import com.aimuceliang.aimuceliang.ui.BaseActivity;
import com.aimuceliang.aimuceliang.ui.adapter.CommonAdapter;
import com.aimuceliang.aimuceliang.ui.adapter.CommonViewHolder;
import com.aimuceliang.aimuceliang.utils.BluetoothChat;
import com.aimuceliang.aimuceliang.utils.SharePreferenceUtil;
import com.aimuceliang.aimuceliang.utils.T;
import com.aimuceliang.aimuceliang.utils.XLog;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;

/**
 * Created by 80470 on 2017/8/12.
 * 测量蓝牙列表页
 */

public class ChooseBluetoothActivity extends BaseActivity {
    private final static String TAG = "ChooseBluetoothActivity";
    @BindView(R.id.turn_on_bluetooth)
    CheckBox btSwith;
    @BindView(R.id.listView)
    ListView deviceList;
    @BindView(R.id.user_name)
    TextView userName;
    private MyAdapter adapter;
    private AlertDialog mDialog;
    public static final int SKIP_ACTIVITY = 100;
    public static final int SCAN_DEV = 101;
    public static final int OPEN_SCAN = 102;

    private int uiDeviceType = 0;  // 0-未知 1-笼秤 2-窝秤 3-体尺
    private LongChengDaoUtils LCDaoUtils;
    private WoChengDaoUtils WCDaoUtils;
    private TiChiCeLiangDaoUtils TCDaoUtils;

    //蓝牙适配器
    private BluetoothAdapter mBtAdapter;
    //蓝牙信息
    private List<BluetoothDevice> blueList;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SKIP_ACTIVITY://设备来连接成功
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    if (msg.obj != null && msg.obj instanceof BluetoothDevice) {
                        toOtherActivity();
                    } else {
                        T.showShort("连接成功 ，数据读取启动异常 请重试");
                    }
                    break;
                case SCAN_DEV:
                    if (!mBtAdapter.isDiscovering()) {
                        mBtAdapter.startDiscovery();
                    }
                    //根据适配器得到所有的设备信息
                    Set<BluetoothDevice> deviceSet = mBtAdapter.getBondedDevices();
                    if (deviceSet.size() > 0) {
                        for (BluetoothDevice device : deviceSet) {
                            if (!blueList.contains(device)) {
                                blueList.add(device);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case OPEN_SCAN:
                    if (!mBtAdapter.isDiscovering()) {
                        mBtAdapter.startDiscovery();
                    }
                    mHandler.sendEmptyMessageDelayed(SCAN_DEV, 2000);
                    break;
                case BluetoothChat.STATUS_CONNECTING:
                    String str = (String) msg.obj;
                    if (str != null && !str.equals("")) {
                        T.showLong(str);
                    }
                    break;
                case BluetoothChat.STATUS_CONNECTERROR:
                    String stringERR = (String) msg.obj;
                    if (stringERR != null && !stringERR.equals("")) {
                        T.showLong(stringERR);
                    }
                    break;
                case BluetoothChat.STATUS_CONNECT:
                    String string = (String) msg.obj;
                    if (string != null && !string.equals("")) {
                        T.showLong(string);
                    }
                    toOtherActivity();
                    break;
                case BluetoothChat.OUTPUT_MESSAGE_SUCESS:
                    String string1 = (String) msg.obj;
                    if (string1 != null && !string1.equals("")) {
                        T.showLong(string1);
                    }
                    break;
                case BluetoothChat.INPUT_MESSAGE_SUCESS:
                    String string2 = (String) msg.obj;
                    if (string2 != null && !string2.equals("")) {
                        T.showLong(string2);
                    }
                    break;
            }
        }
    };

    @Override
    protected int initContentView() {
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }
        return R.layout.activity_choose_bluetooth;
    }

    @Override
    protected void initUIAndListener() {
        setTitle(getIntent().getStringExtra("title"));
        uiDeviceType = Integer.parseInt(getIntent().getStringExtra("DeviceType"));

        userName.setText(SharePreferenceUtil.getUsername(this));
        //蓝牙开关
        btSwith.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mHandler.sendEmptyMessageDelayed(SCAN_DEV, 500);
                } else {
                    blueList.clear();
                    adapter.notifyDataSetChanged();
                }
            }
        });
        View empty = getLayoutInflater().inflate(R.layout.empty_view_btlist, null);
        ((ViewGroup) deviceList.getParent()).addView(empty, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        deviceList.setEmptyView(empty);
        initDialog();

        // 判断是否有为上传的数据
        if (checkUnUploadData(uiDeviceType)) {
            // 需要增加提示对话框，当点击“是”则弹出上传页面，点击“否”则不做任何操作
            // 0-未知 1-笼秤 2-窝秤 3-体尺
            switch (uiDeviceType) {
                case 1:
                    startActivity(LCDataActivity.class);
                    break;
                case 2:
                    startActivity(WCDataActivity.class);
                    break;
                case 3:
                    startActivity(TCDataActivity.class);
                    break;
            }

        }

    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        initBluetooth();//初始化蓝牙
        blueList = new ArrayList<>();
        adapter = new MyAdapter();
        deviceList.setAdapter(adapter);
        adapter.bindData(blueList);
        handleData(title);
        setBluetoothListener();
        registerBroadcast();//新设备机检测
    }

    /**
     * 初始化蓝牙
     */
    public void initBluetooth() {
        if (!mBtAdapter.isEnabled()) {
            btSwith.setChecked(false);
            if (mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
            }
        } else {
            btSwith.setChecked(true);
            mHandler.sendEmptyMessageDelayed(OPEN_SCAN, 2000);
        }
    }

    public void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass().getMethod("removeBond");
            m.invoke(device);
        } catch (Exception e) {

        }
    }

    /**
     * 点击连接对应蓝牙
     */
    private void setBluetoothListener() {
        deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = blueList.get(position);
                // unpairDevice(device);

                //开始连接蓝牙设备
                AlertDialog.Builder stopDialog = new AlertDialog.Builder(ChooseBluetoothActivity.this);
                stopDialog.setTitle("连接");//标题
                stopDialog.setMessage(device.getName());
                stopDialog.setPositiveButton("连接", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //mBtAdapter.cancelDiscovery();
                        BluetoothChat.getBluetoothChat(uiDeviceType).OpenThisDev(device.getAddress(), mHandler);
                        dialog.cancel();
                        if (mDialog != null && !mDialog.isShowing()) {
                            mDialog.show();
                        }
                    }
                });
                stopDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                stopDialog.show();
            }
        });
    }

    /**
     * 连接中dialog
     */
    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.layout_bt_connect, null);
        ProgressBar bar = (ProgressBar) view.findViewById(R.id.bt_connect_bar);
        builder.setView(view);
        builder.setCancelable(false);
        mDialog = builder.create();
    }

    /**
     * 注册广播
     */
    private void registerBroadcast() {
        //设备被发现广播
        IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, discoveryFilter);

        // 设备发现完成
        IntentFilter foundFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, foundFilter);
    }

    /**
     * 发现设备广播
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 获得设备信息
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 如果绑定的状态不一样
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (!blueList.contains(device)) {
                        blueList.add(device);
                    }
                    adapter.notifyDataSetChanged();
                }
                // 如果搜索完成了
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (0 == blueList.size()) {
                    T.showLong("没有发现设备");
                }
            }
        }
    };

    private void toOtherActivity() {
        switch (getIntent().getStringExtra("title")) {
            case "笼秤":
                startActivity(new Intent(ChooseBluetoothActivity.this, LongChengActivity.class));
                break;
            case "窝秤":
                startActivity(new Intent(ChooseBluetoothActivity.this, WoChengActivity.class));
                break;
            case "体尺测量":
                startActivity(new Intent(ChooseBluetoothActivity.this, TiChiActivity.class));
                break;
        }
    }

    private void handleData(String title) {
        switch (title) {
            case "笼秤":

                break;
            case "窝秤":

                break;
            case "体尺测量":

                break;
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, 3);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        this.unregisterReceiver(mReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    public List<BluetoothDevice> removeDuplicate(List<BluetoothDevice> list) {
        Set set = new LinkedHashSet<BluetoothDevice>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }


    /**
     * 列表适配器
     */
    private class MyAdapter extends CommonAdapter<BluetoothDevice> {

        MyAdapter() {
            super(R.layout.bule_item_layout, ChooseBluetoothActivity.this);
        }

        @Override
        public void convert(CommonViewHolder holder, BluetoothDevice bluetoothDevice) {
            Log.d(TAG, "name=" + bluetoothDevice.getName());
            if (bluetoothDevice.getName() == null || bluetoothDevice.getName().isEmpty()) {
                holder.setText(R.id.blue_name, bluetoothDevice.getAddress());
            } else {
                holder.setText(R.id.blue_name, bluetoothDevice.getName());
            }
        }
    }


    private boolean checkUnUploadData(int iDeviceType) {

        boolean bRes = false;

        // 0-未知 1-笼秤 2-窝秤 3-体尺
        switch (iDeviceType) {
            case 1: {
                LCDaoUtils = new LongChengDaoUtils(this);
                if (LCDaoUtils.queryAllLongCheng().size() > 0) {
                    bRes = true;
                }
            }
            break;
            case 2: {
                WCDaoUtils = new WoChengDaoUtils(this);
                if (WCDaoUtils.queryAllWoCheng().size() > 0) {
                    bRes = true;
                }
            }
            break;
            case 3: {
                TCDaoUtils = new TiChiCeLiangDaoUtils(this);
                if (TCDaoUtils.queryAllTiChiCeLiang().size() > 0) {
                    bRes = true;
                }
            }
            break;
            default: {

            }
            break;
        }

        return bRes;
    }

}
